namespace fabao.Common.Util;

public class EnumHelper
{
    /// <summary>
    /// 将枚举转换成字典，键为枚举值，值为枚举描述
    /// </summary>
    /// <returns></returns>
    public static Dictionary<int, string> ToDic<T>() where T : Enum
    {
        T[] values = (T[])Enum.GetValues(typeof(T));
        var dic = new Dictionary<int, string>();

        for (int i = 0; i < values.Length; i++)
        {
            T value = values[i];
            string name = EasyTool.EnumUtil.GetDescription(value);
            int id = Convert.ToInt32(value);

            dic.Add(id, name);
        }

        return dic;
    }

    /// <summary>
    /// 获取EasyTool.DescriptionAttribute标记的枚举描述
    /// </summary>
    /// <param name="enumValue"></param>
    /// <returns></returns>
    public static string GetEnumDescription(object enumValue)
    {
        var fieldInfo = enumValue.GetType().GetField(enumValue.ToString());
        var attribute = fieldInfo.GetCustomAttributes(typeof(EasyTool.DescriptionAttribute), false)
                                 .FirstOrDefault() as EasyTool.DescriptionAttribute;

        return attribute?.Description ?? enumValue.ToString();
    }
}
